package com.sdy.supermarket.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.supermarket.biz.model.*;
import com.sdy.supermarket.biz.mapper.GsUserApplyMapper;
import com.sdy.supermarket.biz.service.GsApproveFlowConfigService;
import com.sdy.supermarket.biz.service.GsApproveFlowTypeService;
import com.sdy.supermarket.biz.service.GsOrderService;
import com.sdy.supermarket.biz.service.GsResService;
import com.sdy.supermarket.biz.service.GsUserApplyService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户申请流程 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2019-07-25
 */
@Slf4j
@Service
public class GsUserApplyServiceImpl extends BaseServiceImpl<GsUserApply> implements GsUserApplyService {
    @Autowired
    private GsUserApplyMapper gsUserApplyMapper;
    @Autowired
    private GsApproveFlowTypeService gsApproveFlowTypeService;
    @Autowired
    private GsResService gsResService;
    @Autowired
    private GsOrderService gsOrderService;
    @Autowired
    private GsApproveFlowConfigService gsApproveFlowConfigService;

    @Override
    public List<GsUserApply> createApply(String orderNo) throws BizException {
        GsOrder gsOrder = gsOrderService.getByOrderNo(orderNo);
        Assert.isNull(gsOrder, "订单不存在！订单[" + gsOrder.getOrderNo() + "]失效！");
        for (GsOrderItem item : gsOrder.getItemList()) {
            GsRes res = gsResService.getById(item.getResId());
            Assert.isNull(res, "资源不存在！订单[" + gsOrder.getOrderNo() + "]失效！");
            @SuppressWarnings("unchecked")
            List<GsApproveFlowConfig> configList = gsApproveFlowConfigService.list(new LambdaQueryWrapper<GsApproveFlowConfig>()
                    .eq(GsApproveFlowConfig::getConfigNo, res.getApConfigNo())
                    .orderByAsc(GsApproveFlowConfig::getSection)
            );
            Assert.isNull(res, "流程不存在！订单[" + gsOrder.getOrderNo() + "]失效！");
            GsApproveFlowType flowType = gsApproveFlowTypeService.getOne(
                    new LambdaQueryWrapper<GsApproveFlowType>().eq(GsApproveFlowType::getType, configList.get(0).getFlowType())
            );
            Assert.isNull(flowType, "审核单类型不存在！订单[" + gsOrder.getOrderNo() + "]失效！");
            GsUserApply apply = new GsUserApply();
            apply.setUserId(gsOrder.getUserId());
            apply.setFlowConfigNo(res.getApConfigNo());
//            apply.setApplyFormId(flowType.get);
            apply.setOrderNo(gsOrder.getOrderNo());
            apply.setState(1);
            apply.setCreateTime(new Date());
        }
        return null;
    }
}
